import time
import datetime
from django.contrib.auth import login, authenticate
from django.core.serializers.json import json
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render

from chdwlgcsys.src.sqlControlFYB import sqlSelectData, sqlUpdateDataLine, sqlInsertDataLine, sqlInsertDataMultLine, \
    sqlDeleteData, colNameMatrxiToString, stringToColNameMatrix
import chdwlgcsys.src.dataToDatabaseCAD as dtdb
from chdwlgcsys.src.sysMain import dbTableHead

# 实现用户登录的功能，
# 返回值有：
def userLogin(request):
    userName = request.POST.get("userAccount")
    userPassword = request.POST.get("userPass")
    csrftoken = request.POST.get("csrfmiddlewaretoken")
    #print(userName,userPassword,csrftoken)
    sqlFetchData = sqlSelectData(dbTableHead + "user_infor", ["user_password", "user_auth", "user_name", "enter_account"],
                                 "user_account='" + userName + "'", dtdb.dataBaseSql['default'])
    #print(userName,userPassword,sqlFetchData)
    if sqlFetchData != 'fail':
        if len(sqlFetchData) > 0:  # 说明该账号在数据库里面有数据
            if userPassword == sqlFetchData[0][0]:  # 用户名和密码正确，查询用户权限，更新dbTableHead+'user_session'表
                updateUserSession(userName, csrftoken)  # 更新dbTableHead + 'user_session'表
                userUrl = sqlSelectData(dbTableHead+"auth_list", ["auth_url"], "auth_name='" + sqlFetchData[0][1] + "'",
                                        dtdb.dataBaseSql['default'])
                tempBakUrl = 'index'
                if len(userUrl) > 0:  # 表明dbTableHead+'auth_list'里面取出了对应角色的数据
                    tempBakUrl = userUrl[0][0]
                tempString = {'loginState': 'success',
                              'locUrl': tempBakUrl,
                              'csrftokenfyb': csrftoken,
                              'userName': sqlFetchData[0][2],
                              'enterAccount': sqlFetchData[0][3],  # 用户所属企业的唯一标识，即企业账号
                              'userAuth': sqlFetchData[0][1],  # 用户权限
                              }
            else:
                tempString = {'loginState': 'nopassword',
                              }  # 密码不正确
        else:
            tempString = {'loginState': 'nouseraccount',
                          }  # 不存在该账号
    bakString = json.dumps(tempString)
    return HttpResponse(bakString)


def updateUserSession(session_key, session_data):
    userSessionData = sqlSelectData(dbTableHead+"user_session", ["session_data"], "session_key='" + session_key + "'",
                                    dtdb.dataBaseSql['default'])
    sessionSaveTime = 604800  # 单位是秒，604800是一周
    updateTime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time() + sessionSaveTime))  # 生成数据的更新时间
    if len(userSessionData) > 0:  # 表明表里面有数据，那么，只要更新session_data和expire_date就可以了
        restraint = "session_key='" + session_key + "'"
        updateSqlData = sqlUpdateDataLine(dbTableHead+'user_session', ["session_data", "expire_date"],
                                          [session_data, updateTime], restraint, dtdb.dataBaseSql['default'])
    else:
        sqlInsertData = sqlInsertDataLine(dbTableHead+'user_session', ["session_data", "session_key", "expire_date"],
                                          [session_data, session_key, updateTime], dtdb.dataBaseSql['default'])


def userLoginVerify(request):
    userAccount = request.POST.get("userAccount")
    userSession = request.POST.get("userSession")
    backState = 'fail'
    if userSession != '':  # 上传的userSession有数据
        sqlFetchData = sqlSelectData(dbTableHead+"user_session", ["session_data", "expire_date"],
                                     "session_key='" + userAccount + "'", dtdb.dataBaseSql['default'])
        if len(sqlFetchData) > 0:  # 表明数据库里面有相应的session数据
            if userSession == sqlFetchData[0][0]:  # 对应session_key(userAccount)的session值与数据库中保存的一致
                expire_date = (sqlFetchData[0][1])  # 过期时间
                now_data = str(datetime.datetime.now())  # 生成数据的创建时间
                if now_data < expire_date:  # 表明session在有效期内
                    backState = 'success'
    bakString = json.dumps({'sessionState': backState,
                            })
    return HttpResponse(bakString)


def userLogout(request):
    userAccount = request.POST.get("userAccount")
    updateTime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time() - 86400))
    restraint = "session_key='" + userAccount + "'"
    bakString = ''
    sqlUpdateDataLine(dbTableHead+'user_session', ["session_data", "expire_date"], ['', updateTime], restraint,
                      dtdb.dataBaseSql['default'])
    return HttpResponse(bakString)


def userRegister(request):
    if request.method == "POST":  # ‘POST’方法传递数据
        sqlType = request.POST.get("sqlType")
        userID = request.POST.get("userID")  # 用户唯一ID
        enterID = request.POST.get("enterID")  # 企业唯一ID
        tableName = request.POST.get("table")  # 操作表格的名称
        columnName = request.POST.get("column")
        userAccount = request.POST.get("userAccount")  # 获取用户账号
        sqlFetchData = sqlSelectData(tableName, ["user_account"], "user_account='" + userAccount + "'",
                                     dtdb.dataBaseSql['default'])
        # print(len(sqlFetchData))
        if len(sqlFetchData) > 0:  # 该账号在数据库中存在
            bakString = json.dumps([{"insert": "0", "status": "fail"}])
        else:
            columnName = columnName + ", data_owner_user_account, creat_user_account, enter_account, creat_time"
            columnNameMatrix = stringToColNameMatrix(columnName)  # 把列的字符串转化为矩阵
            dataInsert = request.POST.get("saveData")
            creatTime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))  # 生成数据的创建时间
            dataInsertMatrix = stringToColNameMatrix(dataInsert)
            dataInsertMatrix.append(userID)
            dataInsertMatrix.append(userID)
            dataInsertMatrix.append('default')  # 默认为default企业，为保留账号企业
            dataInsertMatrix.append(creatTime)
            sqlInsertData = sqlInsertDataLine(tableName, columnNameMatrix, dataInsertMatrix,
                                              dtdb.dataBaseSql['default'])
            bakString = json.dumps([{"insert": sqlInsertData, "status": "success"}])
    print('********loginControlFYB*userRegister*fyb********')
    return HttpResponse(bakString)

def userMenu(request):
    bakString='fail'
    titleData=[]
    titleiClass=[]
    titleHref=[]
    cotentData=[]
    contentiClass=[]
    cotentDataHref=[]
    cotentMenuID=[]
    if request.method == "POST":  # ‘POST’方法传递数据
        userAccount = request.POST.get("userAccount")
        userAuth = request.POST.get("userAuth")
        #到dbTableHead+'user_menu_list'里面查找对应用户账号的菜单目录
        sqlUserMenuData = sqlSelectData(dbTableHead+"user_menu_list", ["menu_name", "menu_url", "menu_iclass_data", "id"], "menu_user='" + userAccount + "' and menu_level=1 order by menu_list_order ASC", dtdb.dataBaseSql['default'])
        if len(sqlUserMenuData)>0:
            for i in range(len(sqlUserMenuData)):#提取第一层目录的基本信息
                titleData.append(sqlUserMenuData[i][0])
                titleiClass.append(sqlUserMenuData[i][2])
                titleHref.append(sqlUserMenuData[i][1])
                #提取第二层目录信息
                sqlMenuLevelUserData=sqlSelectData(dbTableHead+"user_menu_list", ["menu_name", "menu_url", "menu_iclass_data", "id"], "menu_user='" + userAccount + "' and menu_level=2 and menu_father_id='" + sqlUserMenuData[i][3] +"' order by menu_list_order ASC", dtdb.dataBaseSql['default'])
                #print(len(sqlMenuLevelUserData))
                tempCotentData = []
                tempContentiClass = []
                tempCotentDataHref = []
                tempMenuID = []
                if len(sqlMenuLevelUserData)>0:#第二层目录有信息
                    for j in range(len(sqlMenuLevelUserData)):#第二层目录信息
                        tempCotentData.append(sqlMenuLevelUserData[j][0])
                        tempContentiClass.append(sqlMenuLevelUserData[j][2])
                        tempCotentDataHref.append(sqlMenuLevelUserData[j][1])
                        tempMenuID.append(str(sqlMenuLevelUserData[j][3]))
                cotentData.append(tempCotentData)#把第二层第i个目录的子目录名称保存
                contentiClass.append(tempContentiClass)#把第二层第i个目录的子目录class保存
                cotentDataHref.append(tempCotentDataHref)#把第二层第i个目录的子目录url保存
                cotentMenuID.append(tempMenuID)#把第二层第i个目录的menuID保存
        else:#到dbTableHead+'auth_menu_list'里面查询对应权限的菜单目录
            sqlFetchData = sqlSelectData(dbTableHead+"auth_menu_list",
                                         ["menu_name", "menu_url", "menu_iclass_data", "id"],
                                         "menu_auth='" + userAuth + "' and menu_level=1 order by menu_list_order ASC",
                                         dtdb.dataBaseSql['default'])
            if len(sqlFetchData) > 0:
                for i in range(len(sqlFetchData)):  # 提取第一层目录的基本信息
                    titleData.append(sqlFetchData[i][0])
                    titleiClass.append(sqlFetchData[i][2])
                    titleHref.append(sqlFetchData[i][1])
                    # 提取第二层目录信息
                    #print(sqlFetchData)
                    sqlMenuLevel2Data = sqlSelectData(dbTableHead+"auth_menu_list", ["menu_name", "menu_url", "menu_iclass_data", "id"], "menu_auth='" + userAuth + "' and menu_level=2 and menu_father_id='" + str(sqlFetchData[i][3]) + "' order by menu_list_order ASC", dtdb.dataBaseSql['default'])
                    tempCotentData = []
                    tempContentiClass = []
                    tempCotentDataHref = []
                    tempMenuID = []
                    #print(sqlMenuLevel2Data)
                    if len(sqlMenuLevel2Data) > 0:  # 第二层目录有信息
                        for j in range(len(sqlMenuLevel2Data)):  # 第二层目录信息
                            tempCotentData.append(sqlMenuLevel2Data[j][0])
                            tempContentiClass.append(sqlMenuLevel2Data[j][2])
                            tempCotentDataHref.append(sqlMenuLevel2Data[j][1])
                            tempMenuID.append(str(sqlMenuLevel2Data[j][3]))
                    cotentData.append(tempCotentData)  # 把第二层第i个目录的子目录名称保存
                    contentiClass.append(tempContentiClass)  # 把第二层第i个目录的子目录class保存
                    cotentDataHref.append(tempCotentDataHref)  # 把第二层第i个目录的子目录url保存
                    cotentMenuID.append(tempMenuID)  # 把第二层第i个目录的menuID保存
        bakString = json.dumps([{"status": "success", "titleData": titleData, "titleiClass": titleiClass, "titleHref": titleHref, "cotentData": cotentData, "contentiClass": contentiClass, "cotentDataHref":cotentDataHref, "cotentMenuID":cotentMenuID}])
    return HttpResponse(bakString)

def roleAuthMenu(request):#角色目录
    bakString='fail'
    titleData=[]
    titleiClass=[]
    titleHref=[]
    cotentData=[]
    contentiClass=[]
    cotentDataHref=[]
    cotentMenuID=[]
    if request.method == "POST":  # ‘POST’方法传递数据
        userAuth = request.POST.get("userAuth")
        #到dbTableHead+'auth_menu_list'里面查询对应权限的菜单目录
        sqlFetchData = sqlSelectData(dbTableHead+"auth_menu_list", ["menu_name", "menu_url", "menu_iclass_data", "id"], "menu_auth='" + userAuth + "' and menu_level=1 order by menu_list_order ASC", dtdb.dataBaseSql['default'])
        if len(sqlFetchData) > 0:
            for i in range(len(sqlFetchData)):  # 提取第一层目录的基本信息
                titleData.append(sqlFetchData[i][0])
                titleiClass.append(sqlFetchData[i][2])
                titleHref.append(sqlFetchData[i][1])
                # 提取第二层目录信息
                #print(sqlFetchData)
                sqlMenuLevel2Data = sqlSelectData(dbTableHead+"auth_menu_list", ["menu_name", "menu_url", "menu_iclass_data", "id"], "menu_auth='" + userAuth + "' and menu_level=2 and menu_father_id='" + sqlFetchData[i][3] + "' order by menu_list_order ASC", dtdb.dataBaseSql['default'])
                tempCotentData = []
                tempContentiClass = []
                tempCotentDataHref = []
                tempMenuID = []
                #print(sqlMenuLevel2Data)
                if len(sqlMenuLevel2Data) > 0:  # 第二层目录有信息
                    for j in range(len(sqlMenuLevel2Data)):  # 第二层目录信息
                        tempCotentData.append(sqlMenuLevel2Data[j][0])
                        tempContentiClass.append(sqlMenuLevel2Data[j][2])
                        tempCotentDataHref.append(sqlMenuLevel2Data[j][1])
                        tempMenuID.append(sqlMenuLevel2Data[j][3])
                cotentData.append(tempCotentData)  # 把第二层第i个目录的子目录名称保存
                contentiClass.append(tempContentiClass)  # 把第二层第i个目录的子目录class保存
                cotentDataHref.append(tempCotentDataHref)  # 把第二层第i个目录的子目录url保存
                cotentMenuID.append(tempMenuID)  # 把第二层第i个目录的menuID保存
        bakString = json.dumps([{"status": "success", "titleData": titleData, "titleiClass": titleiClass, "titleHref": titleHref, "cotentData": cotentData, "contentiClass": contentiClass, "cotentDataHref":cotentDataHref, "cotentMenuID":cotentMenuID}])
    return HttpResponse(bakString)


def getAuthURL(request):#获取网页的访问用户，是否有该权限访问。根据角色，确定能否访问该网页
    userAccount = request.POST.get("userAccount")#用户的账号
    userAuth = request.POST.get("userAuth")#用户的角色
    fullURL=request.POST.get("userURL")
    fullURL=fullURL.replace("#", "")
    urlMatrix=fullURL.split("/")
    userURL=""
    if(len(urlMatrix)>0):
        userURL=urlMatrix[len(urlMatrix)-1]#请求的URL
    tempURLHead=""
    for i in range(len(urlMatrix)-1):
        tempURLHead=tempURLHead+urlMatrix[i]+"/"
    # print(userAccount,userAuth,userURL)
    sqlFetchData = sqlSelectData(dbTableHead+"auth_url_list", ["url_name", "auth_name"], "auth_url='" + userURL +"'", dtdb.dataBaseSql['default'])
    # print(userName,userPassword,sqlFetchData)
    sqlFetchUrlByAuth=sqlSelectData(dbTableHead+"auth_list", ["auth_url"], "auth_name='" + userAuth + "'",dtdb.dataBaseSql['default'])
    tempString="index.html"#先将返回值设置为首页。
    if(len(sqlFetchData)>0):
        tempString=sqlFetchUrlByAuth[0][0]#将该角色默认登陆页面保存到返回值中
    if sqlFetchData != 'fail':
        if(len(sqlFetchData)>0):#表明数据库里，指定url有记录
            for i in range(len(sqlFetchData)):#查找取回的数据中，有没有指定的角色，有的话，说明该角色可以访问该网页
                if sqlFetchData[i][1]==userAuth:#说明数据库里，userURL有userAuth这个角色，也就是说，userAuth可以访问userURL
                    tempString = userURL#把返回值设置为所需要访问的url
        else:#如果dbTableHead+'auth_url_list'没有url记录，说明该url是不需要权限控制的，可以任意访问
            tempString=userURL
    bakString = json.dumps([{"status": "success", "url": tempURLHead+tempString}])
    return HttpResponse(bakString)

def getRolList(request):#获取角色的列表信息
    if request.method == "POST":  # ‘POST’方法传递数据
        sqlType = request.POST.get("sqlType")
        userAccount = request.POST.get("userAccount")  # 用户唯一ID
        enterAccount = request.POST.get("enterAccount")  # 企业唯一ID
        tableName = dbTableHead+'role_infor' # 操作表格的名称
        if sqlType == "query":  # 查询数据库
            column = request.POST.get("column")
            columnMatrix = stringToColNameMatrix(column)  # 将’name, phoneid, shunxu‘格式转化为List['name', 'phoneid', 'shunxu']
            restraint = request.POST.get("restraint")
            testDataTemp = []  # 新建矩阵，用来保存返回的数据
            sqlFetchData = sqlSelectData(tableName, columnMatrix, restraint, dtdb.dataBaseSql['default'])
            # print(sqlFetchData)
            for i in range(len(sqlFetchData)):  # 遍历取回的数据
                sqlDataDict = {}  # 新建字典
                for j in range(len(columnMatrix)):  # 按照列名称，将数据保存到字典中
                    sqlDataDict[columnMatrix[j]] = sqlFetchData[i][j]
                testDataTemp.append(sqlDataDict)
            if len(sqlFetchData) == 0:  # 如果是空数据
                sqlDataDict = {}  # 新建字典
                for j in range(len(columnMatrix)):  # 按照列名称，将数据保存到字典中
                    sqlDataDict[columnMatrix[j]] = ''
                testDataTemp.append(
                    sqlDataDict)  # testDataTemp=[{"name": 'abc',"result": 'testBack',},{"name": 'abcdd',"result": 'rtg',}]
            bakString = json.dumps(testDataTemp)
    return HttpResponse(bakString)